package main

import (
	"github.com/jinzhu/configor"
	"go-proxy/admin"
	"go-proxy/common"
	"go-proxy/config"
	"go-proxy/proxy"
	"go-proxy/proxy/auth"
	"go-proxy/proxy/router"
	"os"
	"strings"
)

var (
	commandMap = map[string]bool{
		"--config.sys":   false,
		"--config.proxy": false,
	}
)

func main() {
	config.Config = &config.AppConfig{}
	config.ProxyConfigData = &config.ProxyData{}

	handleCommandParam()

	for key, value := range commandMap {
		if value {
			continue
		}

		if key == "--config.sys" {
			err := configor.Load(config.Config, "config.yaml")
			if err != nil {
				panic(err)
			}
		}

		if key == "--config.proxy" {
			err := configor.Load(config.ProxyConfigData, "route-config.yaml")
			if err != nil {
				panic(err)
			}
		}
	}

	err := common.LogInit()
	if err != nil {
		panic(err)
	}

	proxy.InitService()
	proxy.InitRouter()
	proxy.InitRouter()
	proxy.MetricsInit()
	router.InitHandlerMatchRouter()
	auth.InitAuthConfig()

	common.LogInfo("Starting proxy server...")
	go proxy.InitProxy()
	common.LogInfo("Proxy server started.")
	admin.ConsoleServe()
}

func handleCommandParam() {
	if len(os.Args) < 1 {
		return
	}

	for _, arg := range os.Args[1:] {
		if len(arg) < 0 {
			continue
		}

		split := strings.Split(arg, "=")
		_, ok := commandMap[split[0]]
		if ok && split[0] == "--config.sys" && len(split[1]) > 0 {
			commandMap[split[0]] = true
			err := configor.Load(config.Config, split[1])
			if err != nil {
				panic(err)
			}
		}

		if ok && split[0] == "--config.proxy" && len(split[1]) > 0 {
			commandMap[split[0]] = true
			err := configor.Load(config.ProxyConfigData, split[1])
			if err != nil {
				panic(err)
			}
		}
	}
}
